<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Laravel WebSockets 聊天室</title>

    <!-- 样式 -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .chat-box {
            height: 400px;
            overflow-y: auto;
            background-color: #f8f9fa;
            padding: 20px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        .message {
            margin-bottom: 10px;
            padding: 10px;
            border-radius: 5px;
        }
        .message-mine {
            background-color: #e3f2fd;
            text-align: right;
        }
        .message-other {
            background-color: #f1f1f1;
        }
        .username {
            font-weight: bold;
            margin-bottom: 5px;
        }
        .message-content {
            word-break: break-word;
        }
    </style>
</head>
<body>
    <div class="container mt-5">
        <div class="row">
            <div class="col-md-8 offset-md-2">
                <div class="card">
                    <div class="card-header bg-primary text-white">
                        <h3 class="mb-0">Laravel WebSockets 聊天室</h3>
                    </div>
                    <div class="card-body">
                        <div class="chat-box" id="chat-box">
                            <!-- 消息将在这里显示 -->
                        </div>
                        
                        <form id="chat-form">
                            <div class="mb-3">
                                <input type="text" class="form-control" id="username" placeholder="你的昵称" required>
                            </div>
                            <div class="mb-3">
                                <textarea class="form-control" id="message" placeholder="输入消息..." rows="3" required></textarea>
                            </div>
                            <button type="submit" class="btn btn-primary">发送</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 脚本 -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/laravel-echo@1.15.0/dist/echo.iife.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/pusher-js@8.0.2/dist/web/pusher.min.js"></script>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化 Echo
            window.Echo = new Echo({
                broadcaster: 'pusher',
                key: '{{ env("PUSHER_APP_KEY") }}',
                cluster: '{{ env("PUSHER_APP_CLUSTER") }}',
                wsHost: window.location.hostname,
                wsPort: 6001,
                wssPort: 6001,
                forceTLS: false,
                encrypted: false,
                disableStats: true,
                enabledTransports: ['ws', 'wss'],
            });
            
            // 调试连接状态
            window.Echo.connector.pusher.connection.bind('connected', function() {
                console.log('WebSocket连接成功!');
            });
            
            window.Echo.connector.pusher.connection.bind('error', function(error) {
                console.error('WebSocket连接错误:', error);
            });
        
            // 监听聊天频道
            window.Echo.channel('chat')
                .listen('.message.sent', function(data) {
                    console.log('收到消息:', data);
                    addMessage(data.username, data.message, data.username === $('#username').val());
                });
        
            // 添加消息到聊天框
            function addMessage(username, message, isMe) {
                const messageClass = isMe ? 'message-mine' : 'message-other';
                const messageDiv = `
                    <div class="message ${messageClass}">
                        <div class="username">${username}</div>
                        <div class="message-content">${message}</div>
                    </div>
                `;
                $('#chat-box').append(messageDiv);
                $('#chat-box').scrollTop($('#chat-box')[0].scrollHeight);
            }
        
            // 提交表单发送消息
            $('#chat-form').on('submit', function(e) {
                e.preventDefault();
                
                const username = $('#username').val();
                const message = $('#message').val();
                
                if (!username || !message) return;
                
                // 发送消息到服务器
                $.ajax({
                    url: '{{ route('chat.send') }}',
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    data: {
                        username: username,
                        message: message
                    },
                    success: function(data) {
                        $('#message').val(''); // 清空消息输入框
                    },
                    error: function(err) {
                        console.error('发送消息失败:', err);
                        alert('发送消息失败，请重试。');
                    }
                });
            });
        });
    </script>
</body>
</html> 